/**
 * @author thinking
 */
(function(){
    jQuery.fn.comboselect = function(settings){
        settings = jQuery.extend({
            sort: 'both'// which sides to sort: none, left, right, or both
        }, settings);
        
        var leftSelect;
        var rightSelect;
        var addbtn;
        var rembtn;
        
        this.each(function(i, element){
            switch (i) {
                case 0:
                    leftSelect = $(element);
                case 1:
                    rightSelect = $(element);
                    var theForm = $(this).parents('form');
                    theForm.submit(function(){
                        $(element).find('option').each(function(){
                            $(this).attr('selected', 'selected');
                        });
                        return true;
                    });
                case 2:
                    addbtn = $(element);
                case 3:
                    rembtn = $(element);
            }
        });
        
        leftSelect.dblclick(function(){
            addbtn.click();
        });
        
        rightSelect.dblclick(function(){
            rembtn.click();
        });
        
        addbtn.click(function(){
            var leftOpts = leftSelect.find('option:selected');
            rightSelect.append(leftOpts);
            sortBoxes(leftSelect.attr('id'), rightSelect.attr('id'));
        });
        
        rembtn.click(function(){
            var rightOpts = rightSelect.find('option:selected');
            leftSelect.append(rightOpts);
            sortBoxes(leftSelect.attr('id'), rightSelect.attr('id'));
        });
        
        function sortBoxes(leftID, rightID){
            switch (settings.sort) {
                case 'none':
                    var toSort = null;
                case 'left':
                    var toSort = $('#' + leftID);
                    break;
                case 'right':
                    var toSort = $('#' + rightID);
                    break;
                default:
                    var toSort = $('#' + leftID + ', #' + rightID);
            }
            
            if (settings.sort != 'none') {
                toSort.find('option').selso({
                    type: 'alpha',
                    extract: function(o){
                        return $(o).text();
                    }
                });
            }
			setTimeout(function() {
				 $('#' + leftID + ', #' + rightID).find('option:selected').attr('selected','');
			}, 1);             
        }
        return this;
    }
})(jQuery);
